#!/usr/bin/env python

"""
        __author__      = "Vishal Patil"
        __copyright__   = "Copyright (C) 2006 Vishal Patil"
"""

#
#	A simple python program implementing a cubic solver using PGAP.
#	The cubic question whose roots need to be foun is of the form	
#	a*x^3 + b*x^2 + c*x + d
#	The user has to provide the a,b,c and d values
#

from pgap import RandomGenerator
from pgap.impl.CubicSolver import CubicSolverChromosone 
from pgap.impl.CrossoverMutateOperator import CrossoverMutateOperator
from pgap.impl.BestChromosoneSelector import BestChromosonesSelector
from pgap.Configuration import Configuration
from pgap.Genotype import Genotype

a = 1 
b = -6

c = 11
d = 2

#
#	Solving a problem using PGAP involes the following steps
#	1) Create an appropriate Chromosone class for the problem
#	2) Create a configuration object and set the initial population	
#	3) Create genetic operators and add them to the configuration
#	4) Create chromosone selectors and add them to the configuration
#	5) Create a Genotype using the configuration
#	6) Create chromosones, twice the population size, initialize them
#	   to random values and add them to the population		 
#	7) Now keep on evovling the genotype until the chromosone of desire
#	   fitness is obtained
#
def main():
	
	configuration = Configuration()
	configuration.setPopulationSize(50)

	crossoverOp = CrossoverMutateOperator()
	configuration.addGeneticOperator(crossoverOp)		

	chromosoneSel = BestChromosonesSelector()
	configuration.addNaturalSelector(chromosoneSel)	

	geno	= Genotype(configuration)

	for i in range(0,2*geno.getPopulation().getPopulationSize()):
		cubicSolverChromosone = CubicSolverChromosone(a,b,c,d)
		cubicSolverChromosone.setGeneBounds(-10.0,10.0)
		cubicSolverChromosone.setRandomValue()
		geno.getPopulation().addChromosone(cubicSolverChromosone)

	
	for i in range(0,1000):
		geno.evolve()
		geno.getPopulation().getChromosones().sort()
		print geno.getPopulation().getChromosones()[0]

if __name__ == "__main__":
	main()
